package com.zhang.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * User: 张
 * Date: 2024-11-13
 * Time: 20:48
 * Description:
 */
@Component
@ServerEndpoint(value = "/websocket",subprotocols = {"protocol"})
@Slf4j
public class WebSocket {
    private Session session;

    public static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        log.info("webSocket 消息有新推送，连接总数{}",webSocketSet.size());

    }

    @OnClose
    public void onClose( ){
        webSocketSet.remove(this);
        log.info("webSocket 有连接断开，连接总数{}",webSocketSet.size());

    }

    @OnMessage
    public void onMessage(String message ){
        log.info("收到客户端发来的消息{}",message);

    }

    /**
     * 广播发送消息
     * @param message 信息内容
     */
    public static void sendMessage(String message){
        for(WebSocket webSocket:webSocketSet){
            log.info("广播消息{}",message);

            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}